import { uToken, userId } from '@/store/mutation-types'
import storage from '@/utils/storage'
import LoginApi from '@/api/userInfo'
// 登陆成功后执行
const loginSuccess = (commit, data) => {
	let uToken = data.userToken.accessToken;
  // 过期时间30天
  const expiryTime = 30 * 86400 
	
  // 保存tokne到缓存
  storage.set('uToken', uToken) 
  // 记录到store全局变量
  commit('SET_TOKEN', uToken)
}

const user = {
  state: {
    // 用户认证token
    uToken: '',
    // 用户ID
    userId: null,
		userInfo: uni.getStorageSync("userInfo")
  },

  mutations: {
    SET_TOKEN: (state, value) => {
			storage.set("uToken", value)
			state.uToken = value
    },
    SET_USER_ID: (state, value) => {
      state.userId = value
    },
		SET_USER_INFO: (state, value) => {
			if(value) { value.isVIP = value?.userPermissionId >= 3 }
			storage.set("userInfo", value) 
			state.userInfo = value
		},
		SET_USER_INFO_STORAGE:(state,value)=>{
			storage.set("userInfoStorage", value)
		}
  },

  actions: {
    // 用户登录(普通登录: 输入手机号和验证码)
    Login({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.login({ form: data })
          .then(response => {
            const result = response.data
            loginSuccess(commit, result)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 微信小程序一键授权登录(获取用户基本信息)
    LoginMpWx({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.loginMpWx({ form: data }, { isPrompt: false })
          .then(response => {
            const result = response.data
            loginSuccess(commit, result)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 小程序一键授权登录(授权手机号)
    oneKeyLogin({ commit }, data) {
      loginSuccess(commit, data)
    },

    // 退出登录
    Logout({ commit }, data) {
      const store = this;
      return new Promise((resolve, reject) => {
				// 删除缓存中的token和userId
				storage.remove('userInfo')
				storage.remove('userId')
				storage.remove('uToken')
				// 记录到store全局变量
				commit('SET_TOKEN', '')
				commit('SET_USER_ID', '')
				commit('SET_USER_INFO', undefined)
				uni.reLaunch({
					url: '/pages/index/index'
				})
				resolve()
      })
    }

  }
}

export default user
